package com.example.tms.controller;


import com.example.tms.bean.*;
import com.example.tms.mapper.*;
import com.example.tms.tools.GlobalParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.tms.annotation.*;
@RestController
public class RepairController {

    private RepairVMapper repairVMapper;
    private RepairMapper repairMapper;
    private RepairProjectMapper repairProjectMapper;
    private DriverMapper driverMapper;
    private FileMapper fileMapper;

    @Autowired
    public RepairController(RepairVMapper repairVMapper, RepairMapper repairMapper, RepairProjectMapper repairProjectMapper, DriverMapper driverMapper,FileMapper fileMapper) {
        this.repairVMapper = repairVMapper;
        this.repairMapper = repairMapper;
        this.repairProjectMapper = repairProjectMapper;
        this.driverMapper = driverMapper;
        this.fileMapper = fileMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询维修信息列表兼搜索
    @RequestMapping(value = "repairinfos",method = RequestMethod.GET)
    public List<RepairView> getRepairInfoAll(@RequestParam(value = "pageNum", defaultValue = "1") String pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "0") String pageSize,
                                             @RequestParam(required = false, defaultValue = "") String numberPlate,
                                             @RequestParam(required = false, defaultValue = "") String repairType,
                                             @RequestParam(required = false, defaultValue = "") String repairProjectName){

        //规格定义
        Specification<RepairView> specification = new Specification<RepairView>() {
            /**
             * 构造断言
             * @param root 实体对象引用
             * @param query 规则查询对象
             * @param cb 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<RepairView> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>(); //所有的断言
                if(!numberPlate.equals("")&&numberPlate!=null){ //添加断言
                    Predicate likeNumberPlate = cb.like(cb.lower(root.get("numberPlate").as(String.class)),"%" +numberPlate.toLowerCase()+"%");
                    predicates.add(likeNumberPlate);
                }
                if(!repairType.equals("")&&repairType!=null){ //添加断言
                    Predicate equalRepairType = cb.equal(root.get("repairType").as(String.class), repairType);
                    predicates.add(equalRepairType);
                }
                if(!repairProjectName.equals("") && repairProjectName != null) {
                    CriteriaBuilder.In<String> in = cb.in(root.get("repairId").as(String.class));
                    List<RepairProject> repairProjects = new ArrayList<>();
                    if (!repairProjectName.equals("其它")) {
                        repairProjects = repairProjectMapper.findByRepairProjectNameAndSfcz(repairProjectName, true);
                    } else if (repairProjectName.equals("其它")) {
                        repairProjects = repairProjectMapper.findBySfqt(true);
                    }
                    if (repairProjects != null && repairProjects.size() > 0) {
                        for (RepairProject repairProject : repairProjects) {
                            RepairView repairView = repairVMapper.findByRepairIdAndSfcz(repairProject.getRepairId(), true);
                            in.value(repairView.getRepairId());
                        }
                        predicates.add(in);
                    } else {
                        predicates.add(cb.equal(root.get("repairId").as(String.class), 1));
                    }
                }
                predicates.add(cb.equal(root.get("sfcz").as(Boolean.class),true));
                Predicate[] p = new Predicate[predicates.size()];
                query.where(cb.and(predicates.toArray(p)));
                query.orderBy(cb.desc(root.get("lasttime")));
                return query.getRestriction();
            }
        };
        //分页信息
        Pageable pageable = new PageRequest(Integer.valueOf(pageNum)-1,Integer.valueOf(pageSize)); //页码：前端从1开始，jpa从0开始，做个转换
        Page<RepairView> result= repairVMapper.findAll(specification,pageable); //查询
        List<RepairView> repairViews = result.getContent();//获取Content
        for (RepairView repairView:repairViews){
            List<RepairProject>repairProjects = repairProjectMapper.findByRepairIdAndSfcz(repairView.getRepairId(),true);
            repairView.setRepairProject(repairProjects);
        }
        return repairViews;
    }

    @RequestMapping(value = "repairinfos/{repairId}",method = RequestMethod.GET)
    public RepairView getRepairInfoOne(@PathVariable String repairId){
        RepairView repairView = repairVMapper.findByRepairIdAndSfcz(repairId,true);
        repairView.setRepairProject(repairProjectMapper.findByRepairIdAndSfcz(repairId,true));
        return repairView;
    }
//司机提交维修申请
    @MonitorRequest
    @RequestMapping(value = "repairinfos",method = RequestMethod.POST)
    public List<Map<String,Object>> saveCarinfo(@RequestBody RepairInfo repairInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if (repairInfo.getRepairProject().size()==0){
            map.put("repairProject", "0");
        }
        if(repairInfo.getRepairType()==null&&!checkRepairType(repairInfo.getRepairType())){
            map.put("repairType", "0");
        }
        if(repairInfo.getRepairType().equals("内部维修")&&!checkInternalRepairFactory(repairInfo.getInternalRepairFactory())){
            map.put("internalRepairFactory", "0");
        }
        if(repairInfo.getSubscribeTime()==null){
            map.put("subscribeTime", "0");
        }else if(repairInfo.getSubscribeTime()!=null&&!repairInfo.getSubscribeTime().equals("")){
            String yuyueDatetime = repairInfo.getSubscribeTime();
            if(yuyueDatetime.compareTo(GlobalParam.getSRq1())<0){
                map.put("subscribeTime", "1");
            }
        }
        if(repairInfo.getMileagePicture()==null){
            map.put("mileagePicture", "0");
        }
        if(repairInfo.getRepairPartPicture()==null){
            map.put("repairPartPicture", "0");
        }


        list.add(map);
        if(map.isEmpty()){
            //根据当前用户存clid、sjid（当前用户必须是司机）
            Subject subject = SecurityUtils.getSubject();
            UserView userView = (UserView) subject.getPrincipal();
            DriverInfo driverInfo =  driverMapper.findBySfzhAndSfcz(userView.getYhm(),true);
            if(driverInfo.getClid()==null||driverInfo.getClid().equals("")){
                repairInfo.setCarId("");
            }else {
                repairInfo.setCarId(driverInfo.getClid());
            }
            if(driverInfo.getSjid()==null||driverInfo.getSjid().equals("")){
                repairInfo.setDriverId("");
            }else {
                repairInfo.setDriverId(driverInfo.getSjid());
            }
            repairInfo.setRepairInfoStatus("已提交");
            repairInfo.setLasttime(GlobalParam.getTime());
            repairInfo.setApplyDate(GlobalParam.getSRq());
            repairInfo.setSfcz(true);
            repairMapper.save(repairInfo);
            logger.info("新建维修管理"+repairInfo.toString());
            for (RepairProject repairProject :repairInfo.getRepairProject()){
                if(!repairProject.getRepairProjectName().equals("发动机保养")&&!repairProject.getRepairProjectName().equals("正常维修")&&!repairProject.getRepairProjectName().equals("主车四轮轮毂保养")&&!repairProject.getRepairProjectName().equals("J026挂六轮轮毂保养")&&!repairProject.getRepairProjectName().equals("机油5万1次")&&!repairProject.getRepairProjectName().equals("前二轮轮毂保养")){
                    repairProject.setSfqt(true);
                }else {
                    repairProject.setSfqt(false);
                }
                repairProject.setLasttime(GlobalParam.getTime());
                repairProject.setSfcz(true);
                repairProject.setRepairId(repairInfo.getRepairId());
                repairProjectMapper.save(repairProject);
                FileInfo fileInfo1 = fileMapper.findByFileurl(repairInfo.getMileagePicture());
                fileInfo1.setSfcz(true);
                fileMapper.saveAndFlush(fileInfo1);
                FileInfo fileInfo2 = fileMapper.findByFileurl(repairInfo.getRepairPartPicture());
                fileInfo2.setSfcz(true);
                fileMapper.saveAndFlush(fileInfo2);
            }
        }
        return list;
    }
//维修主管审核
    @MonitorRequest
    @RequestMapping(value = "repairinfos/review/",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateCarinfoSh(@RequestBody RepairInfo repairInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if (repairInfo.getRepairId()==null){
            map.put("repairId", "0");
        }
        if(repairInfo.getAuditOpinion()==null&&repairInfo.getAuditOpinion().equals("")&&!checkAuditOpinion(repairInfo.getAuditOpinion())){
            map.put("auditOpinion", "0");
        }
        if((repairInfo.getAuditOpinion().equals("不受理")||repairInfo.getAuditOpinion().equals("不同意"))&&(repairInfo.getRemark().equals("")||repairInfo.getRemark()==null)){
            map.put("remark", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            Subject subject = SecurityUtils.getSubject();
            UserView userView = (UserView) subject.getPrincipal();
            RepairInfo repairInfo1 = repairMapper.findOne(repairInfo.getRepairId());
            repairInfo1.setAuditOpinion(repairInfo.getAuditOpinion());
            repairInfo1.setRemark(repairInfo.getRemark());
//            repairInfo1.setRepairMileagePicture(repairInfo.getRepairMileagePicture());
//            repairInfo1.setRepairFactoryPicture(repairInfo.getRepairFactoryPicture());
//            repairInfo1.setItudePicture(repairInfo.getItudePicture());
            repairInfo1.setRepairMileage(repairInfo.getRepairMileage());
            repairInfo1.setAuditName(userView.getZsxm());
            repairInfo1.setDateOfAudit(GlobalParam.getSRq());
            repairInfo1.setRepairInfoStatus("已审核");
            repairInfo1.setLasttime(GlobalParam.getTime());
            repairInfo1.setSfcz(true);
            repairMapper.saveAndFlush(repairInfo1);
            logger.info("审核维修管理"+repairInfo.toString());
        }
        return list;
    }

//外部维修司机提交
    @MonitorRequest
    @RequestMapping(value = "repairinfos/submit/",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateCarinfoTj(@RequestBody RepairInfo repairInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if (repairInfo.getRepairId()==null){
            map.put("repairId", "0");
        }
        if(repairInfo.getRepairDateStart()==null||repairInfo.getRepairDateStart().equals("")){
            map.put("repairDateStart", "0");
        }
        if(repairInfo.getRepairDateEnd()==null||repairInfo.getRepairDateEnd().equals("")){
            map.put("repairDateEnd", "0");
        }
        if(repairInfo.getRepairMileagePicture()==null||repairInfo.getRepairMileagePicture().equals("")){
            map.put("repairMileagePicture", "0");
        }
        if(repairInfo.getRepairFactoryPicture()==null||repairInfo.getRepairFactoryPicture().equals("")){
            map.put("repairFactoryPicture", "0");
        }
        if(repairInfo.getItudePicture()==null||repairInfo.getItudePicture().equals("")){
            map.put("itudePicture", "0");
        }
        if(repairInfo.getRepairPlace()==null||repairInfo.getRepairPlace().equals("")){
            map.put("repairPlace", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            RepairInfo repairInfo1 = repairMapper.findOne(repairInfo.getRepairId());
            repairInfo1.setRepairDateStart(repairInfo.getRepairDateStart());
            repairInfo1.setRepairDateEnd(repairInfo.getRepairDateEnd());
            repairInfo1.setRepairMaterialCostSum(repairInfo.getRepairMaterialCostSum());
            repairInfo1.setRepairTimeCostSum(repairInfo.getRepairTimeCostSum());
            repairInfo1.setRepairCostSum(repairInfo.getRepairCostSum());
            repairInfo1.setRepairPlace(repairInfo.getRepairPlace());
            repairInfo1.setRepairScenePicture(repairInfo.getRepairScenePicture());
            repairInfo1.setRepairBillPicture(repairInfo.getRepairBillPicture());
            repairInfo1.setRepairMileagePicture(repairInfo.getRepairMileagePicture());
            repairInfo1.setRepairFactoryPicture(repairInfo.getRepairFactoryPicture());
            repairInfo1.setItudePicture(repairInfo.getItudePicture());
            repairInfo1.setRepairMileage(repairInfo.getRepairMileage());
            repairInfo1.setRepairInfoStatus("已完成");
            repairInfo1.setLasttime(GlobalParam.getTime());
            repairInfo1.setSfcz(true);
            repairMapper.saveAndFlush(repairInfo1);
            logger.info("审核维修管理"+repairInfo.toString());
            FileInfo fileInfo1 = fileMapper.findByFileurl(repairInfo.getRepairMileagePicture());
            fileInfo1.setSfcz(true);
            fileMapper.saveAndFlush(fileInfo1);
            FileInfo fileInfo2 = fileMapper.findByFileurl(repairInfo.getRepairBillPicture());
            fileInfo2.setSfcz(true);
            fileMapper.saveAndFlush(fileInfo2);
            FileInfo fileInfo3 = fileMapper.findByFileurl(repairInfo.getRepairScenePicture());
            fileInfo3.setSfcz(true);
            fileMapper.saveAndFlush(fileInfo3);
            FileInfo fileInfo4 = fileMapper.findByFileurl(repairInfo.getRepairFactoryPicture());
            fileInfo4.setSfcz(true);
            fileMapper.saveAndFlush(fileInfo4);
            FileInfo fileInfo5 = fileMapper.findByFileurl(repairInfo.getItudePicture());
            fileInfo5.setSfcz(true);
            fileMapper.saveAndFlush(fileInfo5);
            List<RepairProject>repairProjects = repairInfo.getRepairProject();
            for (RepairProject repairProject:repairProjects){
               RepairProject repairProject1 =  repairProjectMapper.findByrepairProjectNameAndRepairId(repairInfo.getRepairId(),repairProject.getRepairProjectName());
               repairProject1.setRepairCost(repairProject.getRepairCost());
               repairProjectMapper.saveAndFlush(repairProject1);
            }
        }
        return list;
    }

    //检查维修类型格式
    private Boolean checkRepairType(String repairType){
        Boolean b = false;
        if(repairType.equals("内部维修")||repairType.equals("外部维修")){
            b = true;
        }
        return b;
    }

    //检查内部维修厂格式
    private Boolean checkInternalRepairFactory(String internalRepairFactory){
        Boolean b = false;
        if(internalRepairFactory.equals("嘉兴")||internalRepairFactory.equals("杭州")||internalRepairFactory.equals("上海")||internalRepairFactory.equals("武汉")||internalRepairFactory.equals("广州")||internalRepairFactory.equals("宁波")){
            b = true;
        }
        return b;
    }

    //检查主管审核意见格式
    private Boolean checkAuditOpinion(String auditOpinion){
        Boolean b = false;
        if(auditOpinion.equals("受理")||auditOpinion.equals("不受理")||auditOpinion.equals("同意")||auditOpinion.equals("不同意")){
            b = true;
        }
        return b;
    }
}
